package com.timguan.render.dataprocessor.filter;

import com.timguan.render.dataapi.domain.CmsDataDO;
import com.timguan.render.dataprocessor.processor.DataProcessor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 时间过滤器
 */
public class TimeVaildFilter implements DataFilter {
    private static final Logger logger = LoggerFactory.getLogger(TimeVaildFilter.class);

    @Override
    public List<CmsDataDO> doFilter(List<CmsDataDO> cmsDataDOList, Map<String, String> params) {
        List<CmsDataDO> result = null;
        if (cmsDataDOList == null) {
            return null;
        }
        result = new ArrayList<CmsDataDO>();
        long startDisplayTime = System.currentTimeMillis(), endDisplayTime = 0L;
        try {
            if (params != null) {
                //产生时间交集
                startDisplayTime = StringUtils.isNotBlank(params.get(DataProcessor.START_DISPLAY_TIME)) ?
                        Long.parseLong(params.get(DataProcessor.START_DISPLAY_TIME)) : System.currentTimeMillis();
                endDisplayTime = StringUtils.isNotBlank(params.get(DataProcessor.END_DISPLAY_TIME)) ?
                        Long.parseLong(params.get(DataProcessor.END_DISPLAY_TIME)) : System.currentTimeMillis();
            }
        } catch (Exception e) {
            logger.error("parse params failed!", e);
        }
        for (CmsDataDO cmsDataDO : cmsDataDOList) {
            if (cmsDataDO.getStarttime() != null && cmsDataDO.getEndtime() != null) {
                if (cmsDataDO.getEndtime().getTime() >= startDisplayTime &&
                        (endDisplayTime == 0L || endDisplayTime >= cmsDataDO.getStarttime().getTime())) {
                    result.add(cmsDataDO);
                }
            } else {
                result.add(cmsDataDO);
            }
        }
        return result;
    }
}
